package com.sls.nzdapplication.ui.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment;
import com.esri.arcgisruntime.concurrent.ListenableFuture;
import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.geometry.Point;
import com.esri.arcgisruntime.geometry.PointCollection;
import com.esri.arcgisruntime.geometry.Polyline;
import com.esri.arcgisruntime.geometry.PolylineBuilder;
import com.esri.arcgisruntime.geometry.SpatialReference;
import com.esri.arcgisruntime.geometry.SpatialReferences;
import com.esri.arcgisruntime.layers.WebTiledLayer;
import com.esri.arcgisruntime.location.LocationDataSource;
import com.esri.arcgisruntime.mapping.ArcGISMap;
import com.esri.arcgisruntime.mapping.Basemap;
import com.esri.arcgisruntime.mapping.GeoElement;
import com.esri.arcgisruntime.mapping.Viewpoint;
import com.esri.arcgisruntime.mapping.view.DefaultMapViewOnTouchListener;
import com.esri.arcgisruntime.mapping.view.Graphic;
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay;
import com.esri.arcgisruntime.mapping.view.IdentifyGraphicsOverlayResult;
import com.esri.arcgisruntime.mapping.view.IdentifyLayerResult;
import com.esri.arcgisruntime.mapping.view.LocationDisplay;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.esri.arcgisruntime.symbology.PictureMarkerSymbol;
import com.esri.arcgisruntime.symbology.SimpleLineSymbol;
import com.esri.arcgisruntime.symbology.SimpleRenderer;
import com.hmy.popwindow.PopItemAction;
import com.hmy.popwindow.PopWindow;
import com.sls.nzdapplication.R;
import com.sls.nzdapplication.app.MySharedPreferences;
import com.sls.nzdapplication.db.utils.DyEquipmentLineUtil;
import com.sls.nzdapplication.db.utils.DyEquipmentUtil;
import com.sls.nzdapplication.db.utils.MeterBoxUtil;
import com.sls.nzdapplication.db.utils.SwitchUtil;
import com.sls.nzdapplication.model.DyEquipment;
import com.sls.nzdapplication.model.DyEquipmentLine;
import com.sls.nzdapplication.model.MeterBox;
import com.sls.nzdapplication.model.Switch;
import com.sls.nzdapplication.tiandimap.TianDiTuMethodsClass;
import com.sls.nzdapplication.ui.custom.AddByqView;
import com.sls.nzdapplication.ui.custom.AddDbView;
import com.sls.nzdapplication.ui.custom.AddDljView;
import com.sls.nzdapplication.ui.custom.AddDyView;
import com.sls.nzdapplication.ui.custom.AddFzxView;
import com.sls.nzdapplication.ui.custom.AddQdView;
import com.sls.nzdapplication.ui.custom.AddQzjView;
import com.sls.nzdapplication.ui.custom.GPSView;
import com.sls.nzdapplication.ui.custom.MapLayer;
import com.sls.nzdapplication.ui.custom.MapLayerView;
import com.sls.nzdapplication.ui.custom.MoreIconView;
import com.sls.nzdapplication.util.DeviceUtils;
import com.sls.nzdapplication.util.Utils;
import com.sls.nzdapplication.myapp.ZDAPP;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutionException;

import es.dmoral.toasty.Toasty;
import me.jessyan.autosize.internal.CustomAdapt;

/**
 * 这是一个地图展示类，主要功能是展示地图，定位，添加图层，添加设备等。
 * 其中使用了ArcGIS地图SDK，通过调用SDK的方法实现地图的展示，定位等功能。
 * 同时，该类还实现了GPSView.OnGPSViewClickListener, View.OnClickListener, MapLayerView.OnMapLayerListener, MapLayer.MapLayerClickEvent等接口，
 * 实现了对GPSView，MapLayerView等控件的监听。
 * */
public class DyMapActivity extends AppCompatActivity implements GPSView.OnGPSViewClickListener, View.OnClickListener, MapLayerView.OnMapLayerListener, MapLayer.MapLayerClickEvent  {

    private GraphicsOverlay graphicsOverlay;

    private LocationDisplay mlocationDisplay;

    private MapView mMapView;

    private LocationDisplay mLocationDisplay;

    private final static String TAG = "arcgisMap";

    private AddDljView addDljView;

    private AddByqView addByqView;

    private AddFzxView addFzxView;

    private AddDyView addDyView;

    private AddQzjView addQzjView;

    private AddQdView addQdView;

    private AddDbView addDbView;

    private String lineId;

    private DyEquipment clickEquipment;

    private DyEquipmentUtil equipmentUtil;

    private DyEquipmentLineUtil equipmentLineUtil;

    private MapLayer mapLayer;
    private PopWindow popupWindow;

    private Switch clickSwitch;
    private MoreIconView moreIconView;

    private MapLayerView mapLayerView;

    private ImageView centerPointView;
    private TextView qdEquipment;
    private MeterBoxUtil meterBoxUtil;
    private DrawerLayout drawerLayout;

    private GPSView mGpsView;
    private JSONObject clickEquipmentjs = new JSONObject();

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dy_map);
        mMapView = findViewById(R.id.map_view);
        WebTiledLayer webTiledLayer = TianDiTuMethodsClass.CreateTianDiTuTiledLayer(TianDiTuMethodsClass.LayerType.TIANDITU_VECTOR_2000);
        Basemap tdtBasemap = new Basemap(webTiledLayer);
        WebTiledLayer webTiledLayer1 = TianDiTuMethodsClass.CreateTianDiTuTiledLayer(TianDiTuMethodsClass.LayerType.TIANDITU_VECTOR_ANNOTATION_CHINESE_2000);
        tdtBasemap.getBaseLayers().add(webTiledLayer1);

        ArcGISRuntimeEnvironment.setLicense("runtimelite,1000,rud4449636536,none,NKMFA0PL4S0DRJE15166");
        mMapView.setAttributionTextVisible(false);
        ArcGISMap map = new ArcGISMap(tdtBasemap);
        mMapView.setMap(map);
        graphicsOverlay = new GraphicsOverlay(GraphicsOverlay.RenderingMode.STATIC);

        startLocation();

        mMapView.setOnTouchListener(new DefaultMapViewOnTouchListener(this, mMapView){
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                //获取屏幕点击坐标
                android.graphics.Point mapPoint =  new android.graphics.Point((int)e.getX(),(int)e.getY());
                //将屏幕坐标 传入 identifyGraphicsOverlaysAsync （屏幕坐标，范围，包括图形和弹出窗口时为false，最大检索数）
                final ListenableFuture<List<IdentifyGraphicsOverlayResult>> listListenableFuture = this.mMapView.identifyGraphicsOverlaysAsync(mapPoint,12, false, 1);
                //添加点击事件
                listListenableFuture.addDoneListener(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            //获取点击的范围列表
                            List<IdentifyGraphicsOverlayResult> identifyLayerResults = listListenableFuture.get();
                            //循环图层
                            for (IdentifyGraphicsOverlayResult identifyLayerResult : identifyLayerResults) {
                                //循环所点击要素
                                for (final GeoElement geoElement : identifyLayerResult.getGraphics()) {
                                    if(geoElement.getGeometry().getGeometryType().toString().equals("POINT")){
                                        Log.e(TAG,"当前点击的"+geoElement.getAttributes());
                                        clickEquipmentjs = new JSONObject();
                                        clickEquipmentjs.put("id",geoElement.getAttributes().get("id").toString());
                                        clickEquipmentjs.put("title",geoElement.getAttributes().get("title").toString());
                                        clickEquipmentjs.put("name",geoElement.getAttributes().get("name").toString());
                                        if(!geoElement.getAttributes().get("title").toString().equals("MeterBox")) {
                                            clickEquipment = equipmentUtil.listOneDyEquipment(geoElement.getAttributes().get("id").toString());
                                            qdEquipment.setText("当前设备：" + clickEquipment.getName()+"【点击查看详情】");
                                        }else{
                                            Intent intent = new Intent(DyMapActivity.this,MeterBoxActivity.class);
                                                            intent.putExtra("equipmentId",clickEquipmentjs.getString("id"));
                                                            startActivity(intent);
                                        }
                                    }
                                }
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (ExecutionException e) {
                            e.printStackTrace();
                        }
                    }
                });
                return super.onSingleTapUp(e);
            }

            @Override
            public void onLongPress(MotionEvent e) {
                // 获取长按时的屏幕坐标
                android.graphics.Point longPressPoint = new android.graphics.Point((int) e.getX(), (int) e.getY());
                // 将屏幕坐标转换为地图上的经纬度坐标
                Point mapPoint = mMapView.screenToLocation(longPressPoint);
                // 获取经纬度坐标
                double longitude = mapPoint.getX();
                double latitude = mapPoint.getY();
                // 创建一个弹窗
                AlertDialog.Builder builder = new AlertDialog.Builder(DyMapActivity.this);
                builder.setMessage("经度: " + longitude + "\n纬度: " + latitude)
                        .setTitle("修改当前设备经纬度")
                        .setCancelable(true)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                //获取选中经纬度，重新设置。 实现设备可移动功能
                                clickEquipment.setLat(latitude);
                                clickEquipment.setLon(longitude);
                                if (clickEquipmentjs.containsKey("title")) {
                                    Intent intent;
                                    if (clickEquipmentjs.get("title").equals("MeterBox")) {
                                        intent = new Intent(DyMapActivity.this, MeterBoxActivity.class);
                                    } else if (clickEquipmentjs.get("title").equals("配电箱") || clickEquipmentjs.get("title").equals("变压器")) {
                                        intent = new Intent(DyMapActivity.this, PdxEquipmentActivity.class);
                                    } else {
                                        intent = new Intent(DyMapActivity.this, DyEquipmentActivity.class);
                                    }
                                    //                                    // 添加设备ID和经纬度
                                    intent.putExtra("equipmentId", clickEquipmentjs.getString("id"));

                                    startActivity(intent);
                                    Toasty.success(getApplicationContext(), "经纬度修改成功", Toast.LENGTH_LONG, true).show();

                                }
                            }
                        });

                AlertDialog alert = builder.create();
                alert.show();

            }
        });

        initView();
        initListener();
        initData();
    }


    private void startLocation() {
        mLocationDisplay = mMapView.getLocationDisplay();
        mLocationDisplay.setAutoPanMode(LocationDisplay.AutoPanMode.RECENTER);
        //当我们执行LocationDisplay.startAsync()方法时候，会在地图上显示出我们当前位置
        mLocationDisplay.startAsync();

        //获取的点是基于当前地图坐标系的点
        Point point = mLocationDisplay.getMapLocation();
        Log.e("xyh", "point: " + point.toString());

        //获取基于GPS的位置信息
        LocationDataSource.Location location = mLocationDisplay.getLocation();
        //基于WGS84的经纬度坐标。
        Point point1 = location.getPosition();
        if (point1 != null) {
            Log.e("xyh", "point1: " + point1.toString());
        }

        //如果要在LocationDisplay里进行位置信息的自动监听，方法也很简单，只需要LocationDisplay.addLocationChangedListener即可
        mLocationDisplay.addLocationChangedListener(new LocationDisplay.LocationChangedListener() {
            @Override
            public void onLocationChanged(LocationDisplay.LocationChangedEvent locationChangedEvent) {
                LocationDataSource.Location location = locationChangedEvent.getLocation();
                Geocoder geocoder = new Geocoder(getApplicationContext());

//                try {
//                    new MySharedPreferences(getApplicationContext()).saveAddress(geocoder.getFromLocation(location.getPosition().getY(),location.getPosition().getX(),1).get(0).getAddressLine(0));
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
                List<Address> addresses = null;
                try {
                    // 尝试根据位置的经纬度获取地址信息
                    addresses = geocoder.getFromLocation(location.getPosition().getY(), location.getPosition().getX(), 1);
                } catch (IOException e) {
                    // 处理地理编码时可能出现的IO异常
                    e.printStackTrace();
                }
                if (!addresses.isEmpty()) {
                    // 如果成功获取地址信息，将其保存到SharedPreferences
                    new MySharedPreferences(getApplicationContext()).saveAddress(addresses.get(0).getAddressLine(0));
                }
            }
        });
    }

    private void initView(){
        addByqView = findViewById(R.id.add_byq);
        addFzxView = findViewById(R.id.add_fzx);
        addDyView = findViewById(R.id.add_dy);
        addDljView = findViewById(R.id.add_dlj);
        addQzjView = findViewById(R.id.add_qzj);
        addQdView = findViewById(R.id.add_qd);
        addDbView = findViewById(R.id.add_db);
        centerPointView = findViewById(R.id.center_point);
        mapLayer = findViewById(R.id.map_layer_view);
        qdEquipment = findViewById(R.id.qd_equipment);
        moreIconView = findViewById(R.id.miv);
        mapLayerView = findViewById(R.id.mv);
        mapLayer.setMapLayerClickEvent(this);
        drawerLayout = findViewById(R.id.drawer_layout);
        mGpsView = (GPSView) findViewById(R.id.gps_view);
    }

    private void initData() {
        Intent intent = getIntent();
        lineId = intent.getStringExtra("lineId");
        new InitOverTask().execute();

    }

    private void initListener(){
        addByqView.setOnClickListener(this);
        addFzxView.setOnClickListener(this);
        addDyView.setOnClickListener(this);
        addDljView.setOnClickListener(this);
        addQzjView.setOnClickListener(this);
        addQdView.setOnClickListener(this);
        addDbView.setOnClickListener(this);
        moreIconView.setOnClickListener(this);
        qdEquipment.setOnClickListener(this);
        mGpsView.setOnGPSViewClickListener(this);
        mapLayerView.setOnMapLayerListener(this);
        equipmentUtil = new DyEquipmentUtil(getApplicationContext());
        equipmentLineUtil = new DyEquipmentLineUtil(getApplicationContext());
        meterBoxUtil = new MeterBoxUtil(getApplicationContext());
    }


    @Override
    protected void onPause() {
        super.onPause();
        mMapView.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.resume();
        new InitOverTask().execute();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.dispose();
    }

    @Override
    public void onMapLayerClick() {
        drawerLayout.openDrawer(Gravity.RIGHT);
    }

    @Override
    public void openMapLayer(String type) {
        if(type.equals("default")){

            WebTiledLayer webTiledLayer = TianDiTuMethodsClass.CreateTianDiTuTiledLayer(TianDiTuMethodsClass.LayerType.TIANDITU_VECTOR_2000);
            Basemap tdtBasemap = new Basemap(webTiledLayer);
            WebTiledLayer webTiledLayer1 = TianDiTuMethodsClass.CreateTianDiTuTiledLayer(TianDiTuMethodsClass.LayerType.TIANDITU_VECTOR_ANNOTATION_CHINESE_2000);
            tdtBasemap.getBaseLayers().add(webTiledLayer1);

            ArcGISMap map = new ArcGISMap(tdtBasemap);
            mMapView.setMap(map);
            centerPointView.setBackgroundResource(R.drawable.center_point);
            startLocation();
        }else{
            WebTiledLayer webTiledLayer2 = TianDiTuMethodsClass.CreateTianDiTuTiledLayer(TianDiTuMethodsClass.LayerType.TIANDITU_IMAGE_2000);
            Basemap tdtBasemap2 = new Basemap(webTiledLayer2);
            WebTiledLayer webTiledLayer22 = TianDiTuMethodsClass.CreateTianDiTuTiledLayer(TianDiTuMethodsClass.LayerType.TIANDITU_IMAGE_ANNOTATION_CHINESE_2000);
            tdtBasemap2.getBaseLayers().add(webTiledLayer22);

            ArcGISMap map = new ArcGISMap(tdtBasemap2);
            mMapView.setMap(map);

            centerPointView.setBackgroundResource(R.drawable.center_yellow);
            startLocation();
        }
    }

    @Override
    public void openOverLayer(List<String> actives) {

    }

    @Override
    public void openofflineMap() {

    }

    @Override
    public void onClick(View view) {
        if(view == addByqView){

            if(equipmentUtil.queryDyEquipmentByAreaIdAndByq(lineId).size()==2){
                Toasty.info(getApplicationContext(),"台区内已存在变压器", Toast.LENGTH_SHORT,true).show();
                return;
            }
            if(clickEquipment!=null && !clickEquipment.getType().equals("配电箱")){
                Toasty.info(getApplicationContext(),"该设备无法作为配电箱的前端设备",Toast.LENGTH_SHORT,true).show();
                return;
            }

            //选择出线开关
            newByq(ZDAPP.EQUIPMENT_BYQ);
            return;
        }
        if(view == addFzxView){
            if(equipmentUtil.queryDyEquipmentByAreaId(lineId).size()==0){
                Toasty.info(getApplicationContext(),"请先新建配电箱",Toast.LENGTH_SHORT,true).show();
                return;
            }
            newEquipment(ZDAPP.EQUIPMENT_FZX);
            return;
        }
        if(view == addDyView){
            if(equipmentUtil.queryDyEquipmentByAreaId(lineId).size()==0){
                Toasty.info(getApplicationContext(),"请先新建配电箱",Toast.LENGTH_SHORT,true).show();
                return;
            }
            newEquipment(ZDAPP.EQUIPMENT_DY);
            return;
        }
        //电缆井
        if(view == addDljView){
            if(equipmentUtil.queryDyEquipmentByAreaId(lineId).size()==0){
                Toasty.info(getApplicationContext(),"请先新建配电箱",Toast.LENGTH_SHORT,true).show();
                return;
            }
            newEquipment(ZDAPP.EQUIPMENT_DLJ);
            return;
        }

        if(view == addQzjView){
            if(equipmentUtil.queryDyEquipmentByAreaId(lineId).size()==0){
                Toasty.info(getApplicationContext(),"请先新建配电箱",Toast.LENGTH_SHORT,true).show();
                return;
            }
            newEquipment(ZDAPP.EQUIPMENT_QZJ);
            return;
        }
        if(view == addQdView){
            if(equipmentUtil.queryDyEquipmentByAreaId(lineId).size()==0){
                Toasty.info(getApplicationContext(),"请先新建配电箱",Toast.LENGTH_SHORT,true).show();
                return;
            }
            newEquipment(ZDAPP.EQUIPMENT_QD);
            return;
        }
        if(view == addDbView){
            if(equipmentUtil.queryDyEquipmentByAreaId(lineId).size()==0){
                Toasty.info(getApplicationContext(),"请先新建变压器",Toast.LENGTH_SHORT,true).show();
                return;
            }
            newMeterBox(ZDAPP.EQUIPMENT_DB);
            return;
        }



        if(view == moreIconView){
            Intent intent = new Intent(DyMapActivity.this,DyManagementActivity.class);
            intent.putExtra("areaId",lineId);
            startActivity(intent);
        }
        if(view == qdEquipment){
            if(clickEquipmentjs.containsKey("title") ){
                if( clickEquipmentjs.get("title").equals("MeterBox")) {
                    Intent intent = new Intent(DyMapActivity.this,MeterBoxActivity.class);
                    intent.putExtra("equipmentId",clickEquipmentjs.getString("id"));
                    startActivity(intent);
                }
                else if(clickEquipmentjs.get("title").equals("配电箱") || clickEquipmentjs.get("title").equals("变压器")){
                    Intent intent = new Intent(DyMapActivity.this,PdxEquipmentActivity.class);
                    intent.putExtra("equipmentId",clickEquipmentjs.getString("id"));
                    startActivity(intent);}
                else {
                    Intent intent = new Intent(DyMapActivity.this,DyEquipmentActivity.class);
                    intent.putExtra("equipmentId",clickEquipmentjs.getString("id"));
                    startActivity(intent);
                }
            }

        }
    }

    private void newByq(String type){
        if(clickEquipment!=null && (clickEquipment.getType().equals("配电箱") || clickEquipment.getType().equals("变压器"))){
            initSwitch(type);
            if(clickSwitch == null){
                return;
            }
        }
        openByqEquipmentActivity(type);
    }

    private void openByqEquipmentActivity(String type){
        Point point = getMapCenterPoint();
        Intent intent = new Intent(DyMapActivity.this,PdxEquipmentActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("type",type);
        bundle.putString("lineId",lineId);
        bundle.putBoolean("new",true);
        bundle.putDouble("lat", point.getY());
        bundle.putDouble("lon", point.getX());
        bundle.putString("clickE",clickEquipment==null?"":clickEquipment.getId());
        bundle.putString("clickS",clickSwitch==null?"":clickSwitch.getId());
        intent.putExtra("params",bundle);
        clickSwitch=null;
        startActivity(intent);
    }

    private void openEquipmentActivity(String type){
        Point point = getMapCenterPoint();
        Intent intent = new Intent(DyMapActivity.this,DyEquipmentActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("type",type);
        bundle.putString("lineId",lineId);
        bundle.putBoolean("new",true);
        bundle.putDouble("lat", point.getY());
        bundle.putDouble("lon", point.getX());
        bundle.putString("clickE",clickEquipment==null?"":clickEquipment.getId());
        bundle.putString("clickS",clickSwitch==null?"":clickSwitch.getId());
        intent.putExtra("params",bundle);
        clickSwitch=null;
        startActivity(intent);
    }


    private void newEquipment(String type){

        if(clickEquipment!=null && clickEquipment.getType().equals("配电箱")){
            initSwitch(type);
            if(clickSwitch == null){
                return;
            }
        }
        openEquipmentActivity(type);
    }


    private void initSwitch(String type){
        SwitchUtil switchUtil = new SwitchUtil(getApplicationContext());
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,600);
        List<String> swName = new ArrayList<>();
        ListView listView = new ListView(getApplicationContext());
        listView.setLayoutParams(layoutParams);
        List<Switch> switchList = switchUtil.querySwitchByeId(clickEquipment.getId());

        for(Switch sw:switchList){
            swName.add(sw.getName());
        }
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                clickSwitch = switchList.get(i);
                if(type.equals("配电箱")){
                    openByqEquipmentActivity(type);
                }else{
                    openEquipmentActivity(type);
                }
                popupWindow.dismiss();
            }
        });

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                getApplicationContext(), android.R.layout.simple_list_item_1, swName);
        listView.setAdapter(adapter);
        popupWindow= new PopWindow.Builder(DyMapActivity.this)
                .setStyle(PopWindow.PopWindowStyle.PopAlert)
                .setMessage("请选择出线开关")
                .addContentView(listView)
                .setIsShowCircleBackground(false)
                .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Warning))
                .setPopWindowMarginsF(DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),200), DeviceUtils.dip2px4View(getApplicationContext(),30), DeviceUtils.dip2px4View(getApplicationContext(),0))
                .show();
    }

    private void newMeterBox(String type){
        Point point = getMapCenterPoint();
        Intent intent = new Intent(DyMapActivity.this,MeterBoxActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("type",type);
        bundle.putString("lineId",lineId);
        bundle.putBoolean("new",true);
        bundle.putDouble("lat", point.getY());
        bundle.putDouble("lon", point.getX());
        bundle.putString("clickS",clickSwitch==null?"":clickSwitch.getId());
        bundle.putString("clickE",clickEquipment==null?"":clickEquipment.getId());
        intent.putExtra("params",bundle);
        clickSwitch=null;
        startActivity(intent);
    }

    /**
     *
     * func:获取屏幕中心的经纬度坐标
     * @return 经纬度
     */ public Point getMapCenterPoint() {
        int left = mMapView.getLeft();
        int top = mMapView.getTop();
        int right = mMapView.getRight();
        int bottom = mMapView.getBottom();
        // 获得屏幕点击的位置
        int x = (int) (mMapView.getX() + (right - left) / 2);
        int y = (int) (mMapView.getY() + (bottom - top) / 2);
        return mMapView.screenToLocation(new android.graphics.Point(x,y));
    }

    private void initOverLayer(){
        mMapView.getGraphicsOverlays().clear();
        initEquipment();
        initChannel();


    }

    private void initEquipment(){
        graphicsOverlay = new GraphicsOverlay(GraphicsOverlay.RenderingMode.STATIC);
        List<DyEquipment> equipmentList = equipmentUtil.queryDyEquipmentByAreaId(lineId);
        addEquipmentMarkPoint(equipmentList,R.drawable.bdzmap);

        List<MeterBox> meterBoxes = meterBoxUtil.queryMeterBoxByLineId(lineId);
        addMeterBoxMarkPoint(meterBoxes,R.drawable.bx);
        mMapView.getGraphicsOverlays().add(graphicsOverlay);
    }

    private void addEquipmentMarkPoint(List<DyEquipment> equipmentList, int drawable) {
        for (DyEquipment equipment : equipmentList) {
            if (null != equipment.getLat()) {
                drawable = ZDAPP.EquipmentMapDrawable.get(equipment.getType());
                Bitmap bitmap =  Utils.getMardBitmap(equipment.getName(),drawable,getApplicationContext());
                PictureMarkerSymbol simpleMarkerSymbol= new PictureMarkerSymbol(new BitmapDrawable(bitmap));
                float offset = Float.valueOf(bitmap.getWidth())/Float.valueOf(bitmap.getHeight());
                //两种分辨率下使用不同的diy参数显示mark点
//                simpleMarkerSymbol.setOffsetX((offset*(4.7f+offset/15f))*(float)1.3888);
                simpleMarkerSymbol.setOffsetX((offset*(4.7f+offset/15f))*(float)0.92);
                simpleMarkerSymbol.setOffsetY(7f);
                Graphic graphic = new Graphic(new Point(equipment.getLon(),equipment.getLat()),simpleMarkerSymbol);
                graphic.getAttributes().put("title",equipment.getType());
                graphic.getAttributes().put("id",equipment.getId());
                graphic.getAttributes().put("name",equipment.getName());
                graphicsOverlay.getGraphics().add(graphic);
            }
        }

    }

    private void addMeterBoxMarkPoint(List<MeterBox> equipmentList, int drawable) {

        for (MeterBox equipment : equipmentList) {
            if (null != equipment.getLat()) {
                try{
                    Bitmap bitmap =  Utils.getMardBitmap(equipment.getBoxCode(),drawable,getApplicationContext());
                    PictureMarkerSymbol simpleMarkerSymbol= new PictureMarkerSymbol(new BitmapDrawable(bitmap));
                    float offset = Float.valueOf(bitmap.getWidth())/Float.valueOf(bitmap.getHeight());
                    //两种分辨率下使用不同的diy参数显示mark点
//                    simpleMarkerSymbol.setOffsetX((offset*(4.7f+offset/15f))*(float)1.3888);
                    simpleMarkerSymbol.setOffsetX((offset*(4.7f+offset/15f))*(float)0.92);
                    simpleMarkerSymbol.setOffsetY(7f);
                    Graphic graphic = new Graphic(new Point(equipment.getLon(),equipment.getLat()),simpleMarkerSymbol);
                    graphic.getAttributes().put("title","MeterBox");
                    graphic.getAttributes().put("id",equipment.getId());
                    graphic.getAttributes().put("name",equipment.getBoxCode());
                    graphicsOverlay.getGraphics().add(graphic);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }

    }

    /**
     * 初始化渠道图形覆盖层。
     * 此方法通过查询指定线路ID的设备线路信息，然后根据设备线路的类型和起止设备ID，创建并显示相应的线条图形。
     * 不接受任何参数。
     * 无返回值。
     */
    private void initChannel(){
        // 创建一个静态渲染模式的图形覆盖层
        GraphicsOverlay lineGraphicOverlay = new GraphicsOverlay(GraphicsOverlay.RenderingMode.STATIC);
        // 根据线路ID查询设备线路信息
        List<DyEquipmentLine> equipmentLines = equipmentLineUtil.queryEquipmentLineByLineId(lineId);
        // 打印设备线路数量，用于调试
        System.err.println(equipmentLines.size());
        // 遍历查询到的设备线路
        for(DyEquipmentLine equipmentLine:equipmentLines){
            try{
                SimpleLineSymbol simpleLineSymbol ;
                // 根据设备线路类型设置线条样式
                simpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.parseColor("#00FF00"), 2);
                if(equipmentLine.getType().equals("2")){
                    simpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.parseColor("#0000FF"), 2);
                }else if(equipmentLine.getType().equals("5") || equipmentLine.getType().equals("51")){
                    simpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.parseColor("#A020F0"), 2);
                }
                else if(equipmentLine.getType().equals("3")){
                    simpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.parseColor("#FFFF00"), 2);
                }else if (equipmentLine.getType().equals("4")){
                    simpleLineSymbol = new SimpleLineSymbol(SimpleLineSymbol.Style.SOLID, Color.parseColor("#FFC0CB"), 2);
                }
                // 根据起始设备ID查询并设置起始点坐标
                DyEquipment s = equipmentUtil.listOneDyEquipment(equipmentLine.getStartEquipmentId());
                PolylineBuilder lineGeometry = new PolylineBuilder(SpatialReferences.getWgs84());
                if(s!=null){
                    lineGeometry.addPoint(new Point(s.getLon(),s.getLat()));
                }
                // 根据线路类型和终止设备ID查询并设置终点坐标
                if(equipmentLine.getType().equals("5")){
                    MeterBox meterBox = meterBoxUtil.listOneMeterBox(equipmentLine.getEndEquipmentId());
                    lineGeometry.addPoint(new Point(meterBox.getLon(),meterBox.getLat()));
                }else{
                    DyEquipment e = equipmentUtil.listOneDyEquipment(equipmentLine.getEndEquipmentId());
                    lineGeometry.addPoint(new Point(e.getLon(),e.getLat()));
                }
                // 创建线条图形并添加到图形覆盖层
                Graphic lineGraphic = new Graphic(lineGeometry.toGeometry(),simpleLineSymbol);
                lineGraphicOverlay.getGraphics().add(lineGraphic);

            }catch (Exception e){
                // 打印异常信息，用于调试
                e.printStackTrace();
            }

        }
        // 将图形覆盖层添加到地图视图
        mMapView.getGraphicsOverlays().add(lineGraphicOverlay);
    }

    @Override
    public void onGPSClick() {
        startLocation();
    }


    class InitOverTask extends AsyncTask<Void, Integer, Boolean> {

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected Boolean doInBackground(Void... params) {
            initOverLayer();
            return true;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {

        }

        @Override
        protected void onPostExecute(Boolean result) {
            if(result){
                List<DyEquipment> equipmentList = equipmentUtil.queryDyEquipmentByAreaId(lineId);
                if(equipmentList.size()>0){
                    clickEquipment = equipmentList.get(0);
                    clickEquipmentjs = new JSONObject();
                    clickEquipmentjs.put("id",clickEquipment.getId());
                    clickEquipmentjs.put("title",clickEquipment.getType());
                    clickEquipmentjs.put("name",clickEquipment.getName());
                    qdEquipment.setText("当前设备：" + clickEquipment.getName()+"【点击查看详情】");
                }else{
                    clickEquipment = null;
                    clickEquipmentjs = new JSONObject();
                    qdEquipment.setText("当前设备:");
                }
            }
        }
    }

}